class IMClient {
  constructor() {
    this.socket = null;
    this.connected = false;
    this.username = localStorage.getItem('username');
    this.imSessionToken = localStorage.getItem('imSessionToken');
    this.maxReconnectAttempts = 5;
    this.reconnectAttempts = 0;
    this.reconnectInterval = 3000; // 重连间隔3秒
  }

  /**
   * 初始化WebSocket连接
   */
  init() {
    if (this.connected || !this.username || !this.imSessionToken) {
      return;
    }

    // 构建WebSocket连接地址
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const host = window.location.host;
    const url = `${protocol}//${host}/sso-client-web/ws/im?token=${this.imSessionToken}`;

    try {
      this.socket = new WebSocket(url);
      
      // 连接成功
      this.socket.onopen = () => {
        console.log('WebSocket连接成功');
        this.connected = true;
        this.reconnectAttempts = 0; // 重置重连次数
        
        // 发送上线通知
        this.sendOnlineStatus(true);
      };

      // 接收消息
      this.socket.onmessage = (event) => {
        try {
          const message = JSON.parse(event.data);
          console.log('收到消息:', message);
          
          // 触发自定义事件，让组件可以监听
          const customEvent = new CustomEvent('imMessage', { detail: message });
          window.dispatchEvent(customEvent);
        } catch (error) {
          console.error('解析消息失败:', error);
        }
      };

      // 连接关闭
      this.socket.onclose = (event) => {
        console.log(`WebSocket连接关闭，代码: ${event.code}, 原因: ${event.reason}`);
        this.connected = false;
        
        // 发送下线通知
        this.sendOnlineStatus(false);
        
        // 自动重连
        this.reconnect();
      };

      // 连接错误
      this.socket.onerror = (error) => {
        console.error('WebSocket错误:', error);
        this.connected = false;
      };
    } catch (error) {
      console.error('初始化WebSocket失败:', error);
      this.reconnect();
    }
  }

  /**
   * 发送消息
   */
  sendMessage(message) {
    if (!this.connected || !this.socket) {
      console.error('WebSocket未连接，无法发送消息');
      return false;
    }

    try {
      const msg = {
        type: 'chat',
        from: this.username,
        to: message.to,
        content: message.content,
        timestamp: Date.now()
      };
      
      this.socket.send(JSON.stringify(msg));
      return true;
    } catch (error) {
      console.error('发送消息失败:', error);
      return false;
    }
  }

  /**
   * 发送在线状态
   */
  sendOnlineStatus(online) {
    if (!this.username) return;

    try {
      const statusMsg = {
        type: 'status',
        username: this.username,
        online: online,
        timestamp: Date.now()
      };
      
      if (this.connected && this.socket) {
        this.socket.send(JSON.stringify(statusMsg));
      }
    } catch (error) {
      console.error('发送在线状态失败:', error);
    }
  }

  /**
   * 重连机制
   */
  reconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('达到最大重连次数，停止重连');
      return;
    }

    setTimeout(() => {
      this.reconnectAttempts++;
      console.log(`尝试重连(${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
      this.init();
    }, this.reconnectInterval);
  }

  /**
   * 关闭连接
   */
  close() {
    if (this.socket) {
      this.socket.close(1000, '主动关闭连接');
      this.connected = false;
      this.socket = null;
    }
  }
}

export default IMClient;
    